﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using Telerik.Web.UI;
using KPIS.GERP.GIMS.DAL;
using KPIS.GERP.GIMS.MODEL;
using System.Collections.Generic;
using System.Web.UI.WebControls;

namespace KPIS.GERP.GIMS.APP.APP_UI.Edit_Form
{
    public partial class ICM_Requisition : System.Web.UI.Page
    {
        Common.Main main = new Common.Main();
        D_IcmMasResourceItem d_resource_item = new D_IcmMasResourceItem();
        M_IcmMasResourceItem m_resource_item = new M_IcmMasResourceItem();
        D_IcmMasObjectType d_object_type = new D_IcmMasObjectType();
        M_IcmMasObjectType m_object_type = new M_IcmMasObjectType();
        D_Employee d_employee = new D_Employee();
        M_Employee m_employee = new M_Employee();
        D_Requisition d_request = new D_Requisition();
        M_Requisition m_request = new M_Requisition();
        D_Requisition_Desc d_request_desc = new D_Requisition_Desc();
        M_Requisition_Desc m_request_desc = new M_Requisition_Desc();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadToLabel();
                hStatus.Text = Request.QueryString["status"];
                LoadGrid();
                grdRequisition.DataBind();
                UpdateUI("Load");
                if (hStatus.Text == "Edit")
                {
                    pRequisitionNo.Text = Request.QueryString["Requsition_Code"].ToString();
                    LoadcaseMasterEdit();
                    SetObjectEnableTab1(false);
                }
            }
        }
        private void LoadcaseMasterEdit()
        {
            M_Requisition info = d_request.GetListTransferFillBySeq(pRequisitionNo.Text);
            txtDescription.Text = info.description.ToString();
            txtRemark.Text = info.remark.ToString();
            cmbObjectType.SelectedValue = info.icm_obj_type_seq.ToString();
            cmbObjectType.Text = info.icm_obj_type_name.ToString();
        }
        private void LoadToLabel()
        {
            pEmployee.Text = main.EmployeeName();
            pEmpPosition.Text = main.EmployeePositionName();
            pOrganize.Text = main.OrganizeName();
            pApproveName.Text = main.ApproveName();
            pApprovePos.Text = main.ApprovePositionName();
            pRequisitionDate.Text = DateTime.Now.ToShortDateString();
            pRequisitionNo.Text = fncGenerate_RequisitionCode();
        }
        private void SetObjectEnableTab2(Boolean pFlag)
        {

        }
        protected void btnNext_OnClick(object sender, EventArgs e)
        {
            if (ValidateCreateRequest())
            {
                M_Requisition info = d_request.GenerateRequisitionCode();
                m_request.requisition_code = pRequisitionNo.Text;
                m_request.requisition_date = Convert.ToDateTime(pRequisitionDate.Text);
                m_request.request_emp_seq = main.UserID;
                m_request.description = txtDescription.Text;
                m_request.job_site_seq = main.JobsiteSeq();
                m_request.remark = txtRemark.Text;
                m_request.record_status = "U";
                m_request.approve_emp_seq = main.ApproveSeq();
                m_request.created_by = main.UserID;
                m_request.created_when = DateTime.Now;
                m_request.icm_obj_type_seq = Convert.ToInt32(cmbObjectType.SelectedValue);
                if(hStatus.Text !="Edit")
                d_request.Insert_Requisition(m_request);
                else if (hStatus.Text == "Edit")
                {
                    m_request.updated_by = main.UserID;
                    m_request.updated_when = DateTime.Now;
                    d_request.Update_Requisition(m_request);
                }
                SetObjectEnableTab1(true);
                RadAjaxManager1.Alert("หมายเลขของการเบิกของ: " + pRequisitionNo.Text);
                if (hStatus.Text == "Edit")
                {
                    LoadGrid();
                    grdRequisition.DataBind();
                }
                UpdateUI("ChangeTab");
                RadAjaxManager1.ResponseScripts.Add(@"ChangeTab('Request',1);");
            }

        }
        //protected void btnBack_OnClick(object sender, EventArgs e)
        //{
        //    RadAjaxManager1.ResponseScripts.Add(@"ChangeTab('Create',0);");
        //}
        protected void btnInsert_Click(object sender, EventArgs e)
        {
            UpdateUI("Insert");
        }
        protected void grdRequisition_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName == "DataEdit")
            {
                M_Requisition_Desc info = d_request_desc.GetListFillBySeq(main.ConvertNullInt(grdRequisition.Items[e.Item.ItemIndex]["requisiton_des_item"].Text));
                cmbChooseInventoryItem.SelectedValue = info.icm_res_item_seq.ToString();
                cmbChooseInventoryItem.Text = info.icm_res_item_name.ToString();
                txtQuantity.Text = info.quantity.ToString();
                hrequisiton_des_item.Text = grdRequisition.Items[e.Item.ItemIndex]["requisiton_des_item"].Text;
                //if (e.Item is GridCommandItem)
                //{
                //    GridCommandItem commandItem = e.Item as GridCommandItem;
                //    LinkButton buttonInsert = commandItem.FindControl("btnInsert") as LinkButton;
                //    LinkButton buttonSave = commandItem.FindControl("btnSave") as LinkButton;
                //    LinkButton buttonCancel = commandItem.FindControl("btnCancel") as LinkButton;
                //    buttonInsert.Enabled = false;
                //    buttonSave.Enabled = true;
                //    buttonCancel.Enabled = true;
                //}

                UpdateUI("Edit");
            }
            else if (e.CommandName == "DataDelete")
            {
                UpdateUI("Delete");
                M_Requisition_Desc info = d_request_desc.GetListFillBySeq(main.ConvertNullInt(grdRequisition.Items[e.Item.ItemIndex]["requisiton_des_item"].Text));
                m_request_desc.requisiton_des_item=info.requisiton_des_item;
                m_request_desc.icm_res_item_seq = Convert.ToInt32(info.icm_res_item_seq);
                m_request_desc.quantity = Convert.ToDouble(info.quantity);
                m_request_desc.record_status = "D";
                d_request_desc.Update_RequisitionDesc(m_request_desc);
                LoadGrid();
                DataBind();
            }
        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            m_request_desc.requisition_item = d_request_desc.GetRequestItem(pRequisitionNo.Text);
            m_request_desc.requisition_code = pRequisitionNo.Text;
            m_request_desc.quantity = Convert.ToDouble(txtQuantity.Text);
            m_request_desc.icm_res_item_seq = Convert.ToInt32(cmbChooseInventoryItem.SelectedValue);
            m_request_desc.record_status = "U";
            if (hStatus.Text == "Insert")
                d_request_desc.Insert_Requisition_Desc(m_request_desc);
            else if (hStatus.Text == "Edit")
            {
                m_request_desc.requisiton_des_item= Convert.ToInt32(hrequisiton_des_item.Text);
                d_request_desc.Update_RequisitionDesc(m_request_desc);
            }
                
            UpdateUI("Save");
            LoadGrid();
            grdRequisition.DataBind();
        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {
            UpdateUI("Cancel");
           
        }
        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            //UpdateUI("Edit");

        }
        protected void cmbChooseInventoryItem_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {
            IList<M_IcmMasResourceItem> infoList = d_resource_item.GetListFillByName(e.Text);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            e.EndOfItems = (endOffset == infoList.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbChooseInventoryItem.Items.Add(new RadComboBoxItem(infoList[i].icm_res_item_name, infoList[i].icm_res_item_seq.ToString()));
                TableRow tr = new TableRow();
                TableCell tdCode = new TableCell();
                Label lblCode = new Label();
                lblCode.Text = infoList[i].icm_res_item_code;
                tdCode.Width = Unit.Pixel(200);
                tdCode.Controls.Add(lblCode);
                tr.Cells.Add(tdCode);
                TableCell tdName = new TableCell();
                Label lblName = new Label();
                lblName.Text = infoList[i].icm_res_item_name;
                tdName.Width = Unit.Pixel(200);
                tdName.Controls.Add(lblName);
                tr.Cells.Add(tdName);
                TableCell tdDescr = new TableCell();
                Label lblDescr = new Label();
                lblDescr.Text = infoList[i].icm_res_item_descr;
                tdDescr.Width = Unit.Pixel(200);
                tdDescr.Controls.Add(lblDescr);
                tr.Cells.Add(tdDescr);
                ((Table)cmbChooseInventoryItem.Items[j].FindControl("tableInventoryItem")).Controls.Add(tr);
                j++;
            }

            e.Message = GetStatusMessage(endOffset, infoList.Count);
        }
        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }
        protected void cmbObjectType_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            string strFilter = e.Text;
            IList<M_IcmMasObjectType> infoList = d_object_type.GetListFillByName(strFilter);
            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + 10, infoList.Count);
            e.EndOfItems = endOffset == infoList.Count;

            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbObjectType.Items.Add(new RadComboBoxItem(infoList[i].icm_obj_type_name, infoList[i].icm_obj_type_seq.ToString()));
            }

            e.Message = main.GetStatusMessage(endOffset, infoList.Count);

        }
        protected void grdRequisition_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            LoadGrid();
        }
        private void LoadGrid()
        {
            grdRequisition.DataSource = d_request_desc.GetListFillCode(pRequisitionNo.Text);
        }

        private Boolean ValidateCreateRequest()
        {
            Boolean pFlag = true;
            if (txtDescription.Text == "")
            {
                pFlag = false;
                txtDescription.Focus();
                RadAjaxManager1.Alert("กรุณากรอกเรื่องที่ต้องการขอวัสดุด้วย");
            }
            if (cmbObjectType.SelectedValue == "")
            {
                pFlag = false;
                cmbObjectType.Focus();
                RadAjaxManager1.Alert("กรุณาเลือกประเภทวัสดุที่ต้องการขอด้วย");
            }
            if (txtDescription.Text.Length > 255)
            {
                pFlag = false;
                txtDescription.Focus();
                RadAjaxManager1.Alert("ไม่อนุญาติให้กรอกตัวอักษรเกิน 255 ตัวอักษร");
            }
            return pFlag;
        }
        private void SetObjectEnableTab1(Boolean pFlag)
        {
            txtDescription.Enabled = pFlag;
            cmbChooseInventoryItem.Enabled = pFlag;
            cmbObjectType.Enabled = pFlag;
            txtRemark.Enabled = pFlag;
            txtQuantity.Enabled = pFlag;
        }
        private void EnableObject(Boolean pFlag)
        {
            cmbChooseInventoryItem.Enabled = pFlag;
            txtQuantity.Enabled = pFlag;
        }
        private void ClearObject()
        {
            txtDescription.Text = "";
            cmbChooseInventoryItem.ClearSelection();
            cmbChooseInventoryItem.Text = "";
            txtRemark.Text = "";
            txtQuantity.Text = "";
        }
        private string fncGenerate_RequisitionCode()
        {
            string strMonth = "";
            string strYear = "";
            string strRunning = "";
            string strRequisition = "";
            try
            {
                M_Requisition infoRequisition = d_request.GenerateRequisitionCode();
                strYear = infoRequisition.str_year;
                strMonth = main.ConvertstrMonth(infoRequisition.str_month);
                strRunning = main.ConvertstrRunningFiveDigit(infoRequisition.requisition_running);
                strRequisition = "RQ"+strYear +"-" +strMonth  + "-" + strRunning;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return strRequisition;
        }
        private string GenerateRequisitionCode()
        {
            return "";
        }
        private void UpdateUI(string strCommand)
        {
            switch (strCommand)
            {
                case "Load":
                    ClearObject();
                    SetObjectEnableTab1(true);
                    EnableObject(false);
                    btnInsert.Enabled = true;
                    btnSave.Enabled = false;
                    btnCancel.Enabled = false;
                    break;
                case "Insert":
                    hStatus.Text = "Insert";
                    ClearObject();
                    EnableObject(true);
                    btnInsert.Enabled = false;
                    btnSave.Enabled = true;
                    btnCancel.Enabled = true;
                    break;
                case "Edit":
                    hStatus.Text = "Edit";
                    EnableObject(true);
                    btnInsert.Enabled = false;
                    btnSave.Enabled = true;
                    btnCancel.Enabled = true;
                    break;
                case "Save":
                    hStatus.Text = "";
                    EnableObject(false);
                    btnInsert.Enabled = true;
                    btnSave.Enabled = false;
                    btnCancel.Enabled = false;
                    break;
                case "Cancel":
                    hStatus.Text = "";
                    EnableObject(false);
                    ClearObject();
                    btnInsert.Enabled = true;
                    btnSave.Enabled = false;
                    btnCancel.Enabled = false;
                    break;
                case "Delete":
                    EnableObject(false);
                    ClearObject();
                    btnInsert.Enabled = true;
                    btnSave.Enabled = false;
                    btnCancel.Enabled = false;
                    break;
                case "ChangeTab":
                    EnableObject(false);
                    ClearObject();
                    btnInsert.Enabled = true;
                    btnSave.Enabled = false;
                    btnCancel.Enabled = false;
                    break;
            }
        }

    }
}
